<template>
	<div>
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>商品管理</el-breadcrumb-item>
			<el-breadcrumb-item>商品列表</el-breadcrumb-item>
		</el-breadcrumb>

		<!-- 卡片展示区域 -->
		<el-card class="box-card" shadow="always">
			<!-- 搜索 -->
			<el-row :gutter="20">
				<el-col :span="6">
					<el-input v-model="queryInfo.query" placeholder="请输入内容,enter" clearable @clear="getUserData"
						@keyup.enter.native="getUserData">
						<el-button @click="getUserData" slot="append" icon="el-icon-search"></el-button>
					</el-input>
				</el-col>
				<el-col :span="4">
					<el-button type="primary" @click="addDiologVisible = true">添加商品</el-button>
				</el-col>
			</el-row>
			<!-- 商品列表区 -->
			<el-table class="userData" :data="thingsdata" stripe border style="width: 100%" max-height="350">
				<el-table-column fixed type="index" label="#"> </el-table-column>
				<el-table-column fixed prop="id" label="Id" width="60">
				</el-table-column>
				<el-table-column fixed prop="name" label="名称" width="100">
				</el-table-column>
				<el-table-column prop="price" label="现价" width="120">
				</el-table-column>
				<el-table-column prop="agoprice" label="原价" width="60">
				</el-table-column>
				<el-table-column prop="buynum" label="购买人数" width="100">
				</el-table-column>
				<el-table-column prop="browsenum" label="浏览人数" width="100">
				</el-table-column>
				<el-table-column label="添加时间" :formatter="formataddtime">
				</el-table-column>
				<el-table-column prop="imgs" label="图片集" width="100">
					<template slot-scope="scope">
						<el-image style="width: 40px; height: 40px;margin-left: 10px;" :src="scope.row.imgs.split('||')[0]"
								:preview-src-list="scope.row.imgs.split('||')">
						</el-image>
					</template>
				</el-table-column>
				<el-table-column prop="num" label="现货数量" width="100">
				</el-table-column>
				<el-table-column label="操作"  width="120">
					<template slot-scope="scope">
						<el-tooltip class="item" :enterable="false" effect="dark" content="删除该商品" placement="top">
							<el-button type="danger" size="mini" icon="el-icon-delete" @click="delUsers(scope.row.id)">
							</el-button>
						</el-tooltip>
						<el-tooltip class="item" :enterable="false" effect="dark" content="编辑该商品" placement="top">
							<el-button type="success" @click="editUsers(scope.row)" size="mini" icon="el-icon-edit">
							</el-button>
						</el-tooltip>
					</template>
				</el-table-column>
			</el-table>

			<!-- 分页器 -->
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="queryInfo.pageNum" :page-sizes="pagesizedetail"
				layout="total, sizes, prev, pager, next, jumper" :page-size="queryInfo.pagesize" :total="total">
			</el-pagination>
		</el-card>

		<!-- 添加商品对话框 -->
		<el-dialog class="dilog" title="添加商品"   :visible.sync="addDiologVisible" append-to-body>
			<el-form label-position="left" :model="AddForm" :rules="AddRules" ref="AddForm" :show-message="true" label-width="70px" size="small">
				<el-form-item label="名称" prop="name">
					<el-input v-model="AddForm.name" placeholder="输入名称"></el-input>
				</el-form-item>
				<el-form-item label="现价" prop="price">
					<el-input v-model="AddForm.price" placeholder="输入现价"></el-input>
				</el-form-item>
				<el-form-item label="原价" prop="agoprice">
					<el-input v-model="AddForm.agoprice" placeholder="输入原价"></el-input>
				</el-form-item>
				<el-form-item label="浏览数量" prop="browsenum">
					<el-input v-model="AddForm.browsenum" placeholder="输入浏览数"></el-input>
				</el-form-item>
				<el-form-item label="已购买数量" prop="buynum">
					<el-input v-model="AddForm.buynum" placeholder="输入已购买数量"></el-input>
				</el-form-item>
				<el-form-item label="物品数量" prop="num">
					<el-input v-model="AddForm.num" placeholder="输入物品数量"></el-input>
				</el-form-item>
				<el-form-item label="物品图片" prop="imgs">
					<el-upload
					  class="upload-demo"
					  :headers="headers"
					  drag
					  :file-list="fileList"
					  list-type="picture"
					  action="/api/things/updateImg"
					  :on-success="handleAvatarSuccess"
					  multiple>
					  <i class="el-icon-upload"></i>
					  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					</el-upload>
				</el-form-item>
				<el-form-item label="详细信息">
					<vue-editor v-model="AddForm.content" style="width:88%;margin-left: 6%;" useCustomImageHandler @image-added="handleImageAdded"></vue-editor>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="addDiologVisible = false;">取 消</el-button>
				<el-button type="primary" @click="addDiologVisible = false;uploadthinsData();">确 定</el-button>
			</span>
		</el-dialog>

		<!-- 修改商品对话框 -->
		<el-dialog class="dilog" title="修改商品"   :visible.sync="editdialogVisible" append-to-body>
			<el-form label-position="left" :model="EditForm" :rules="AddRules" ref="EditForm" :show-message="true" label-width="70px" size="small">
				<el-form-item label="名称" prop="name">
					<el-input v-model="EditForm.name" placeholder="输入名称"></el-input>
				</el-form-item>
				<el-form-item label="现价" prop="price">
					<el-input v-model="EditForm.price" placeholder="输入现价"></el-input>
				</el-form-item>
				<el-form-item label="原价" prop="agoprice">
					<el-input v-model="EditForm.agoprice" placeholder="输入原价"></el-input>
				</el-form-item>
				<el-form-item label="浏览数量" prop="browsenum">
					<el-input v-model="EditForm.browsenum" placeholder="输入浏览数"></el-input>
				</el-form-item>
				<el-form-item label="已购买数量" prop="buynum">
					<el-input v-model="EditForm.buynum" placeholder="输入已购买数量"></el-input>
				</el-form-item>
				<el-form-item label="物品数量" prop="num">
					<el-input v-model="EditForm.num" placeholder="输入物品数量"></el-input>
				</el-form-item>
				<el-form-item label="物品图片" prop="imgs">
					<el-upload
					  class="upload-demo"
					  :headers="headers"
					  drag
					  :on-remove="handleRemove"
					  :file-list="EditForm.ImgList"
					  list-type="picture"
					  action="/api/things/updateImg"
					  :on-success="handleAvatarSuccess_edit"
					  multiple>
					  <i class="el-icon-upload"></i>
					  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					</el-upload>
				</el-form-item>
				<el-form-item label="详细信息">
					<vue-editor v-model="EditForm.content" style="width:88%;margin-left: 6%;" useCustomImageHandler @image-added="handleImageAdded"></vue-editor>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editdialogVisible = false;">取 消</el-button>
				<el-button type="primary" @click="editdialogVisible = false;updatethinsData();">确 定</el-button>
			</span>
		</el-dialog>
		<div class="one">
			<el-divider content-position="center" @click="Hitokoto">{{this.hitokoto}}</el-divider>
		</div>
	</div>
</template>

<script>
	import {
		VueEditor
	} from "vue2-editor";
	export default {
		name: 'userlist',
		components: {
			VueEditor
		},
		data() {
			return {
				headers: {
					"Authorization": window.sessionStorage.getItem('token')
				},
				fileList:[],
				//用户列表
				pagesizedetail: [4, 6, 10],
				thingsdata: [],
				queryInfo: {
					//查询关键字
					query: '',
					//当前页数
					pageNum: 1,
					// 每页数据大小
					pagesize: 4
				},
				//数据条数
				total: 0,
				//是否添加用户对话框
				addDiologVisible: false,
				//是否编辑用户对话框
				editdialogVisible: false,
				//验证规则
				AddRules: {
					name: [{
							required: true,
							message: '请输入名称',
							trigger: 'blur'
						},
						{
							min: 2,
							max: 20,
							message: '长度在 2 到 20 个字符',
							trigger: 'blur'
						}
					],
					price: [{
							required: true,
							message: '请输入现价',
							trigger: 'blur'
						}
					],
					
				},
				//添加表单
				AddForm: {
					name:"",
					price:"",
					agoprice:'',
					browsenum:'',
					buynum:'',
					num:'',
					imgs:[],
					content:''
				},
				EditForm: {
					name:"",
					price:"",
					agoprice:'',
					browsenum:'',
					buynum:'',
					num:'',
					imgs:[],
					ImgList:[],
					content:''
				},
				hitokoto: ""
			}
		},
		created() {
			this.getUserData()
			this.Hitokoto()
		},
		methods: {
			formataddtime(row, column) {
				var d = new Date(row.addTime);
				var m = d.getMinutes();
				var s = d.getSeconds();
				m = checkTime(m);
				s = checkTime(s);

				function checkTime(i) {
					if (i < 10) {
						i = "0" + i
					}
					return i
				}
				return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + m +
					':' + s;
			},
			async Hitokoto() {
				let {
					data: res
				} = await this.$http.get("https://v1.hitokoto.cn/?c=d");
				this.hitokoto = res.hitokoto
			},
			async getUserData() {
				if (this.queryInfo.query !== '') {
					this.queryInfo.pageNum = 1;
					this.queryInfo.pagesize = 4;
					this.pagesizedetail = [4]
				} else {
					this.pagesizedetail = [4, 6, 10]
				}
				this.get()
			},
			//监听pagesize改变事件
			async handleSizeChange(sizes) {
				this.queryInfo.pagesize = sizes;
				this.get()
			},
			//监听页码值改变时间
			async handleCurrentChange(sizes) {
				this.queryInfo.pageNum = sizes;
				this.get()
			},
			async get() {
				let {
					data: res
				} = await this.$http.get(
					`/api/things/getThisngs?number=${this.queryInfo.pageNum}&size=${this.queryInfo.pagesize}&query=${this.queryInfo.query}&type=search`
				);
				this.thingsdata = res.data;
				this.total = res.number;
			},
			//监听用户对话框关闭
			addDiologClose() {
				this.$refs.AddForm.resetFields()
			},
			editDilogClose() {
				this.$refs.EditForm.resetFields()
			},
			
			//编辑用户(ok)
			editUsers(data) {
				//处理blob
				// console.log(data);
				var arr = []
				data.imgs = data.imgs.split('||').filter((el,i)=>{
				if(!(el.indexOf('blob')!==-1)){
					arr.push(el)
				}
				})
				data.imgs = arr.join('||')
				// console.log(data);
				this.EditForm.ImgList=[]
				this.editdialogVisible = true;
				this.EditForm.name = data.name;
				this.EditForm.price = data.price;
				this.EditForm.agoprice = data.agoprice;
				this.EditForm.browsenum = data.browsenum;
				this.EditForm.buynum = data.buynum;
				this.EditForm.num = data.num;
				this.EditForm.content = data.detailinfo;
				this.EditForm.id = data.id;
				data.imgs.split('||').forEach((el,i)=>{
					this.EditForm.ImgList.push({
						name:i+".jpg",
						url:el
					})
				})
			
			},
			//自写
			uploadthinsData(){
				this.$refs.AddForm.validate(async valid => {
					if (!valid) {
						this.$message.error('必填项未填')
						this.addDiologVisible = false;
					} else {
						if(this.AddForm.imgs.length<1){
							return this.$message.error('至少上传一张物品相关图片')
						}
						var imgs = this.AddForm.imgs.map(val=>{
							return 'http://localhost:3000'+val
						})
						this.AddForm.imgs = imgs.join('||');
						let {
							data: res
						} = await this.$http.post("/api/things/addthings", this.AddForm);
						if (res.code == "500") {
							this.$message.error(res.text)
						} else {
							this.$message.success(res.text)
							this.addDiologVisible = false;
							this.$refs.AddForm.resetFields();
						}
						this.getUserData();
					}
				})
			},
			//更新视图
			updatethinsData(){
				this.$refs.EditForm.validate(async valid => {
					if (!valid) {
						this.$message.error('必填项未填')
						this.editdialogVisible = false;
					} else {
						// 发起请求
						let arr = [];
						this.EditForm.ImgList.forEach((el,i)=>{
							arr.push(el.url)
						})
						this.EditForm.imgsArr = arr.join('||');
						delete this.EditForm.ImgList;
						let {
							data: res
						} = await this.$http.post("/api/things/updatethings", this.EditForm);
						if (res.code == "201") {
							this.$message.success(res.text);
							this.getUserData();
							this.editdialogVisible = false;
						} else {
							this.$message.error("更改信息失败")
						}
					}
				})
			},
			//删除事件(ok)(ok)
			delUsers(Id) {
				this.$confirm('此操作将删除该物品信息, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(async () => {
					let {
						data: res
					} = await this.$http.post("/api/things/delthings", {
						Id: Id
					});
					this.$message({
						type: 'success',
						message: res.text
					});
					this.getUserData()
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			handleAvatarSuccess(res){
				this.AddForm.imgs.push(res.data)
			},
			handleAvatarSuccess_edit(res){
				 var obj = {}
				 obj.name=Math.random()*Date.now()+'.jpg'
				 obj.url ='http://localhost:3000'+ res.data 
				 this.EditForm.ImgList.push(obj)
			},
			async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
				const formdata = new FormData()
				formdata.append('file', file);
				let res = await this.$http.post('/api/things/imgUpload', formdata);
				Editor.insertEmbed(cursorLocation, 'image', 'http://localhost:3000' + res.data.data);
				resetUploader();
			},
			 handleRemove(file, fileList) {
			   this.EditForm.ImgList = fileList
			}
		}
	}
</script>

<style lang="less" scoped>
	.box-card {
		width: calc(99% - 64px);
		min-height: 480px;
		margin: 25px 0 0 20px;
		position: relative;
		left: 50%;
		transform: translate(-52%);

		.userData {
			margin-top: 10px;
			text-align: center;
		}

		.el-pagination {
			margin-top: 10px;
		}

		.el-pagination__jump {
			line-height: 28px;
		}
	}

	.avatar-uploader {
		display: flex;
		width: 200px;
		height: 40px;
		line-height: 40px;
		justify-content: space-between;
		justify-items: center;

		span {
			display: inline-block;
		}
	}
</style>
